package cn.iocoder.yudao.module.picturebook.service.classhomework;

import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classmember.ClassMemberDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.workmember.WorkMemberDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classmember.ClassMemberMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.readingrecord.ReadingRecordMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.workmember.WorkMemberMapper;
import cn.iocoder.yudao.module.picturebook.service.classmember.ClassMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.picturebook.controller.admin.classhomework.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classhomework.ClassHomeworkDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.classhomework.ClassHomeworkMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 班级作业信息 Service 实现类
 *
 * @author 芋道源码
 */
@Slf4j
@Service
@Validated
public class ClassHomeworkServiceImpl implements ClassHomeworkService {

    @Resource
    private ClassHomeworkMapper classHomeworkMapper;
    @Resource
    private ClassMemberService classMemberService;
    @Resource
    private ClassMemberMapper classMemberMapper;
    @Resource
    private WorkMemberMapper workMemberMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private ReadingRecordMapper readingRecordMapper;

    // ... existing code ...
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createClassHomework(ClassHomeworkSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            log.warn("[createClassHomework] 请求参数不能为空");
            return null;
        }

        try {
            // 插入主作业表
            ClassHomeworkDO classHomework = BeanUtils.toBean(createReqVO, ClassHomeworkDO.class);
            classHomeworkMapper.insert(classHomework);

            // 收集所有 workMemberDO 用于批量插入
            List<WorkMemberDO> workMemberList = new ArrayList<>();

            // 获取班级 ID 列表并校验
            List<Long> classIds = createReqVO.getClassId();
            if (classIds == null || classIds.isEmpty()) {
                return classHomework.getId();
            }

            // 遍历每个班级
            for (Long classId : classIds) {
                if (classId == null) {
                    continue;
                }

                // 获取班级成员列表
                List<ClassMemberDO> classMemberList = classMemberService.getClassByClassId(classId);

                // 班级成员为空则跳过
                if (classMemberList == null || classMemberList.isEmpty()) {
                    continue;
                }

                // 构建作业成员关系
                for (ClassMemberDO classMemberDO : classMemberList) {
                    if (classMemberDO != null && classMemberDO.getUserId() != null) {
                        WorkMemberDO workMemberDO = WorkMemberDO.builder()
                                .classId(classId)
                                .memberId(classMemberDO.getUserId())
                                .workId(classHomework.getId())
                                .stuat(0)
                                .build();
                        workMemberList.add(workMemberDO);
                    }
                }
            }

            // 批量插入作业成员关系
            if (!workMemberList.isEmpty()) {
                try {
                    workMemberMapper.insertBatch(workMemberList);
                } catch (Exception e) {
                    log.error("[createClassHomework] 批量插入作业成员关系失败", e);
                }
            }

            // 返回作业 ID
            return classHomework.getId();
        } catch (Exception e) {
            log.error("[createClassHomework] 创建班级作业失败", e);
            return null;
        }
    }


    @Override
    public void updateClassHomework(ClassHomeworkSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            log.warn("[updateClassHomework] 请求参数不能为空");
            return;
        }
        if (updateReqVO.getId() == null) {
            log.warn("[updateClassHomework] 作业ID不能为空");
            return;
        }

        // 校验存在
        if (classHomeworkMapper.selectById(updateReqVO.getId()) == null) {
            log.warn("[updateClassHomework] 作业不存在，ID：{}", updateReqVO.getId());
            return;
        }
        // 更新
        ClassHomeworkDO updateObj = BeanUtils.toBean(updateReqVO, ClassHomeworkDO.class);
        classHomeworkMapper.updateById(updateObj);
    }

    @Override
    public void deleteClassHomework(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[deleteClassHomework] 作业ID不能为空");
            return;
        }

        // 校验存在
        if (classHomeworkMapper.selectById(id) == null) {
            log.warn("[deleteClassHomework] 作业不存在，ID：{}", id);
            return;
        }
        // 删除
        classHomeworkMapper.deleteById(id);
    }

    @Override
    public void deleteClassHomeworkListByIds(List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            log.warn("[deleteClassHomeworkListByIds] 作业ID列表不能为空");
            return;
        }

        // 删除
        classHomeworkMapper.deleteByIds(ids);
    }


    private void validateClassHomeworkExists(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[validateClassHomeworkExists] 作业ID不能为空");
            return;
        }

        if (classHomeworkMapper.selectById(id) == null) {
            log.warn("[validateClassHomeworkExists] 作业不存在，ID：{}", id);
            return;
        }
    }

    @Override
    public ClassHomeworkDO getClassHomework(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[getClassHomework] 作业ID不能为空");
            return null;
        }

        return classHomeworkMapper.selectById(id);
    }

    @Override
    public PageResult<ClassHomeworkDO> getClassHomeworkPage(ClassHomeworkPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            log.warn("[getClassHomeworkPage] 分页请求参数不能为空");
            return PageResult.empty();
        }

        return classHomeworkMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional
/*
  根据班级ID和用户ID获取班级作业信息

  @param classId 班级ID
 * @param userId 用户ID
 * @return 班级作业数据响应VO列表
 */
    public List<ClassHomeWorkDataRespVO> getClassHomeworkByClassIdAndUserId(Long classId, Long userId) {
        List<ClassHomeWorkDataRespVO> list = new ArrayList<>();

        // 参数校验
        if (classId == null || userId == null) {
            log.warn("[getClassHomeworkByClassIdAndUserId] 参数校验失败，classId: {}, userId: {}", classId, userId);
            return list;
        }

        try {
            // 获取作业成员关系
            List<WorkMemberDO> workMemberDOList = workMemberMapper.getWorkMemberByClassIdAndUserId(classId, userId);
            if (workMemberDOList == null || workMemberDOList.isEmpty()) {
                return list;
            }

            // 提取作业ID列表
            List<Long> workIdList = workMemberDOList.stream()
                    .filter(Objects::nonNull)
                    .map(WorkMemberDO::getWorkId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量获取作业信息
            List<ClassHomeworkDO> classHomeworkDOList = classHomeworkMapper.selectByIds(workIdList);
            if (classHomeworkDOList == null || classHomeworkDOList.isEmpty()) {
                return list;
            }

            // 缓存班级人数
            int classMemberCount = 0;
            try {
                classMemberCount = classMemberMapper.getClassMemberCount(classId);
            } catch (Exception e) {
                log.warn("[getClassHomeworkByClassIdAndUserId] 获取班级成员数量失败，classId: {}", classId, e);
            }

            // 批量获取每个作业的完成人数
            Map<Long, Integer> completeCountMap = new HashMap<>();
            for (ClassHomeworkDO homework : classHomeworkDOList) {
                if (homework != null && homework.getId() != null) {
                    try {
                        int count = workMemberMapper.getWorkMemberCompleteCount(homework.getId(), classId);
                        completeCountMap.put(homework.getId(), count);
                    } catch (Exception e) {
                        log.warn("[getClassHomeworkByClassIdAndUserId] 获取作业完成人数失败，workId: {}, classId: {}", homework.getId(), classId, e);
                        completeCountMap.put(homework.getId(), 0);
                    }
                }
            }

            // 构建作业ID到成员关系的映射
            Map<Long, WorkMemberDO> workMemberMap = workMemberDOList.stream()
                    .filter(Objects::nonNull)
                    .filter(w -> w.getWorkId() != null)
                    .collect(Collectors.toMap(WorkMemberDO::getWorkId, w -> w));

            // 日期格式化
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 开始赋值
            for (ClassHomeworkDO classHomeworkDO : classHomeworkDOList) {
                if (classHomeworkDO == null) {
                    continue;
                }

                ClassHomeWorkDataRespVO vo = new ClassHomeWorkDataRespVO();
                vo.setId(classHomeworkDO.getId());
                vo.setHomeworkName(classHomeworkDO.getHomeworkName());

                if (classHomeworkDO.getDeadline() != null) {
                    vo.setHomeworkDate(classHomeworkDO.getDeadline().toLocalDate().format(formatter));
                }

                WorkMemberDO workMemberDO = workMemberMap.get(classHomeworkDO.getId());
                if (workMemberDO != null && workMemberDO.getStuat() != null && workMemberDO.getStuat() == 1) {
                    vo.setIsFinished(true);
                } else {
                    try {
                        LocalDate deadlineDate = classHomeworkDO.getDeadline().toLocalDate();
                        List<Integer> bookIds = readingRecordMapper.getRecordByUserId(userId, deadlineDate);

                        List<Integer> planBook = parseBookIds(classHomeworkDO.getBookId());
                        if (!planBook.isEmpty() && new HashSet<>(bookIds).containsAll(planBook)) {
                            // 更新状态
                            if (workMemberDO != null && workMemberDO.getMemberWorkId() != null) {
                                workMemberMapper.updateWorkMemberStuat(workMemberDO.getMemberWorkId());
                                vo.setIsFinished(true);
                                // 更新完成人数缓存
                                completeCountMap.put(classHomeworkDO.getId(), completeCountMap.getOrDefault(classHomeworkDO.getId(), 0) + 1);
                            }
                        } else {
                            vo.setIsFinished(false);
                        }
                    } catch (Exception e) {
                        log.warn("[getClassHomeworkByClassIdAndUserId] 检查作业完成状态失败，workId: {}, userId: {}", classHomeworkDO.getId(), userId, e);
                        vo.setIsFinished(false);
                    }
                }

                // 设置完成比例
                int completeCount = completeCountMap.getOrDefault(classHomeworkDO.getId(), 0);
                vo.setCompleteRatio(completeCount + "/" + classMemberCount);

                list.add(vo);
            }
        } catch (Exception e) {
            log.error("[getClassHomeworkByClassIdAndUserId] 获取班级作业信息失败，classId: {}, userId: {}", classId, userId, e);
            return new ArrayList<>(); // 出现异常时返回空列表
        }

        return list;
    }


    // 提取解析书籍ID的逻辑
    private List<Integer> parseBookIds(String bookIdStr) {
        if (bookIdStr == null || bookIdStr.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            return Arrays.stream(bookIdStr.replaceAll("[^0-9,]", "").split(","))
                    .filter(s -> !s.isEmpty())
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .distinct()
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.warn("[parseBookIds] 解析书籍ID失败，bookIdStr: {}", bookIdStr, e);
            return Collections.emptyList();
        }
    }


    /**
     * 获取作业完成情况详情
     *
     * @param classId 班级ID
     * @param workId  作业ID
     * @param userId  用户ID
     * @return 返回作业完成情况的详细响应对象
     */
    @Override
    public ClassHomeWorkDetailRespVO getCompleteRatio(Long classId, Long workId, Long userId) {
        // 参数校验
        if (classId == null || workId == null) {
            log.warn("[getCompleteRatio] 参数校验失败，classId: {}, workId: {}", classId, workId);
            return new ClassHomeWorkDetailRespVO();
        }

        try {
            // 初始化作业详情响应对象
            ClassHomeWorkDetailRespVO classHomeWorkDetailRespVO = new ClassHomeWorkDetailRespVO();
            classHomeWorkDetailRespVO.setClassId(classId);
            classHomeWorkDetailRespVO.setHomeworkDetail(new ArrayList<>());
            classHomeWorkDetailRespVO.setCompleteMember(new ArrayList<>());
            classHomeWorkDetailRespVO.setUnCompleteMember(new ArrayList<>());

            // 1. 获取作业详情
            ClassHomeworkDO classHomeworkDO = classHomeworkMapper.selectById(workId);
            if (classHomeworkDO != null) {
                String bookId = classHomeworkDO.getBookId();
                if (bookId != null && !bookId.trim().isEmpty()) {
                    try {
                        // 解析并获取作业相关的书籍列表
                        List<Integer> planBook = Arrays.stream(bookId.replaceAll("[^0-9,]", "").split(","))
                                .filter(s -> !s.isEmpty())
                                .map(String::trim)
                                .map(Integer::parseInt)
                                .distinct()
                                .collect(Collectors.toList());

                        List<BookDO> bookList = Optional.ofNullable(
                                        bookMapper.selectByIds(planBook.stream()
                                                .map(Long::valueOf)
                                                .collect(Collectors.toList())))
                                .orElse(Collections.emptyList());

                        classHomeWorkDetailRespVO.setHomeworkDetail(bookList);
                    } catch (Exception e) {
                        log.warn("[getCompleteRatio] 解析作业书籍失败，bookId: {}", bookId, e);
                    }
                }
            }

            // 2. 获取该班级的所有人
            List<ClassMemberDO> classMemberDOList = Optional.ofNullable(
                            classMemberMapper.getClassAllMemberByClassId(classId))
                    .orElse(Collections.emptyList());

            // 3. 获取未完成作业的人
            List<WorkMemberDO> unWorkMemberDOList = Optional.ofNullable(
                            workMemberMapper.getWorkMemberUnFinish(classId, workId))
                    .orElse(Collections.emptyList());

            // 将未完成作业的成员ID提取为集合
            Set<Long> unFinishedMemberIds = unWorkMemberDOList.stream()
                    .filter(Objects::nonNull)
                    .map(WorkMemberDO::getMemberId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            // 分别存储未完成和已完成作业的成员
            List<ClassMemberDO> unCompleteMembers = new ArrayList<>();
            List<ClassMemberDO> completeMembers = new ArrayList<>();

            // 根据成员是否在未完成作业的成员ID集合中，将其分类
            for (ClassMemberDO member : classMemberDOList) {
                if (member != null && member.getUserId() != null) {
                    if (unFinishedMemberIds.contains(member.getUserId())) {
                        unCompleteMembers.add(member);
                    } else {
                        completeMembers.add(member);
                    }
                }
            }

            // 设置作业完成情况的成员信息
            classHomeWorkDetailRespVO.setUnCompleteMember(unCompleteMembers);
            classHomeWorkDetailRespVO.setCompleteMember(completeMembers);

            // 返回作业完成情况的详细响应对象
            return classHomeWorkDetailRespVO;
        } catch (Exception e) {
            log.error("[getCompleteRatio] 获取作业完成情况详情失败，classId: {}, workId: {}, userId: {}", classId, workId, userId, e);
            return new ClassHomeWorkDetailRespVO(); // 出现异常时返回空对象
        }
    }
// ... existing code ...


}